package service

import (
	"context"
	"fx_swift_ifcgate_agent/api"
	"fx_swift_ifcgate_agent/pkg/code"
	"fx_swift_ifcgate_agent/pkg/global"
	"fx_swift_ifcgate_agent/pkg/internalerrors"
	"fx_swift_ifcgate_agent/pkg/page"
	"github.com/spf13/cast"
)

type IExchangeSrv interface {
	// 换汇明细列表
	ExchangeCurrencyList(ctx context.Context, req *api.ExchangeCurrencyListReq) (*page.Collection[*api.ExchangeCurrencyListRes], error)
}

type exchangeSrv struct {
}

func NewExchangeSrv() IExchangeSrv {
	return &exchangeSrv{}
}

// 换汇明细列表
func (e *exchangeSrv) ExchangeCurrencyList(ctx context.Context, req *api.ExchangeCurrencyListReq) (*page.Collection[*api.ExchangeCurrencyListRes], error) {
	var (
		account    string
		err        error
		total      int
		resultList []*api.ExchangeCurrencyListRes
	)

	account = ctx.Value("Account").(string)

	collectionDto := &page.Collection[*api.ExchangeCurrencyListRes]{}
	collectionDto.Page = uint64(req.PageNo)
	collectionDto.PageSize = uint64(req.PageSize)

	mod := global.GFDB.Ctx(ctx).Schema("fx").Model("fx.ifcgate_exchange_currency iec")
	mod.LeftJoin("fx.ifcgate_merchant_va_info imvi", "imvi.merchant_no=iec.merchant_no")
	mod.Fields("iec.biz_flow,iec.sell_currency,iec.buy_currency,iec.rate,iec.sell_amount," +
		"iec.buy_amount,iec.status,iec.msg,iec.created_at,imvi.mer_name_en,imvi.mer_name_cn")
	if len(req.Currency) > 0 {
		mod.WhereLike("iec.buy_currency", "%"+req.Currency+"%")
	}
	if len(req.BizFlow) > 0 {
		mod.WhereLike("iec.biz_flow", "%"+req.BizFlow+"%")
	}
	if len(req.Status) > 0 {
		mod.Where("iec.status=?", req.Status)
	}
	if len(req.StartTime) > 0 && len(req.EndTime) > 0 {
		mod.Where("iec.created_at >=? and iec.created_at <=?", req.StartTime+" 00:00:00", req.EndTime+" 23:59:59")
	}
	mod.Where("iec.account=?", account)
	mod.Order("iec.created_at desc")
	mod.Limit(int(page.PageToOffset(uint64(req.PageNo), uint64(req.PageSize))), cast.ToInt(req.PageSize))
	err = mod.ScanAndCount(&resultList, &total, false)
	collectionDto.TotalPage = page.GetTotalPage(uint64(req.PageNo), uint64(req.PageSize), cast.ToInt64(total))
	if err != nil {
		return nil, internalerrors.New(code.ErrUnknown, "数据查询异常")
	}
	collectionDto.Total = cast.ToInt64(total)
	collectionDto.List = resultList

	return collectionDto, err
}
